'use strict';

require('../../assets/scss/entry/common.scss');
require('../../assets/scss/entry/exam.scss');

let $ = jQuery = window.jQuery = window.$ = require('jquery');
require('../../libs/jquery.cookie');
require('../../libs/intense.min');
// let Intense = require('../../libs/intense.min');

import * as api from '../../components/api/index.js';
import url from '../../components/util/url.js';
import util from '../../components/util/util.js';
import Video from '../../components/video/video.js';
let Layer = require('../../libs/layer');
import 'babel-polyfill';

let pageEntry = (function() {
	let currentExamTimes = 0;
	let examQuery = null;
	let nextExamType = 0;
	let userName = localStorage.getItem('userName');
	let examCode = url.getQuery('examCode');
	let userCode = $.cookie('userCode');
	let examType = $.cookie('userType');
	let examStatus = 1;
	let questionType = 0;
	let currentExam = 0;

	return {
		initCheck() {
			let nowUrl = window.location.href;
			util.initLogin(nowUrl,"2");
		},
		initExamInfo() {
			// 获取考试信息
			api.getExamInfo(userCode, userName, examCode).then((resp) => {
				if (resp.ret == "0") {
					let content = resp.content;
					let examQuestionIndex = content.paper.examQuestionIndex;

					currentExam = examQuestionIndex;
					questionType = parseInt(content.paper.questions[currentExam].questionType)-1;

					if (currentExam == 6) {
						examStatus = 2;
					}
					else {
						nextExamType = content.paper.questions[currentExam + 1].answerWay;
					}

					examQuery = {
						studentCode: content.studentCode,
						userCode: content.userCode || '',
						organCode: content.organCode || '',
						paperId: content.paper.id,
						examType: examType,
						questionId: content.paper.questions[currentExam].id,
						examStatus: examStatus,
						questionIndex: parseInt(content.paper.examQuestionIndex) + 1
					};
					var answerDemoUrl = resp.content.paper.questions[currentExam].answerDemoUrl;
					var questionExplainUrl = resp.content.paper.questions[currentExam].questionExplainUrl;


					$('#J_exam_title').html('第'+ util.initToCapitalNumber(currentExam) +'题&nbsp;&nbsp;' + util.initExamTitle(questionType));
					$('#J_answerDemoUrl').find('[data-video-elem="player"]').attr('src', answerDemoUrl);
					$('#J_questionExplainUrl').find('[data-video-elem="player"]').attr('src', questionExplainUrl);
					var examQuestionImageExplainUrl = content.paper.questions[currentExam].questionImageExplainUrl;
					if(!util.isEmpty(examQuestionImageExplainUrl)){
						$('#J_material').find('img').attr('src', content.paper.questions[currentExam].questionImageExplainUrl);
						$('#J_material').find('img').attr('data-rel', content.paper.questions[currentExam].questionImageExplainUrl);
						$('#J_material_wrap').show();
						// Intense( $('#J_material').find('img')[0] );
					}
				}
		    });
		},
		bindEvent() {
			let explainVideo = new Video($('#J_questionExplainUrl'));
			let answerVideo = new Video($('#J_answerDemoUrl'));

			explainVideo.init();
			answerVideo.init();

			var uploadParams = {
			    files: null,
			    storeAs: '',
			    fileSize: 0
			};

			// 初始化阿里OSS
			var ossInstance = new OSS.Wrapper({
			    region: 'oss-cn-beijing',
			    accessKeyId: 'LTAILVutljlBrYZn',
			    accessKeySecret: 'snGmFKg75eP9o5hZE59pOVEM26p0T2',
			    bucket: 'koucaiceping-video'
			});

			var videoSrc = '';

			function loadFile(file) {
		        var $video = $('#J_exam_video').find('.content-video-wrap');

			    var filePath = file.value;
			    var fileExt = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();

			    if (file.files && file.files[0]) {
			        uploadParams.files = file.files[0];
			        uploadParams.storeAs = '/kcx-video/ceping/test/'+ Math.random()*10000 +'.mp4';
			        uploadParams.fileSize = file.files[0].size;

			        $(file).prop('disabled', true);
			        $('#J_exam_video').show();
			        $video.hide();
			        $('#J_exam_video').find('.content-video-loading').show()

			        ossInstance.multipartUpload(uploadParams.storeAs, uploadParams.files, {
		                progress: function* (p) {
		                	var percent = parseInt(p * 100);
		                    $('#J_exam_video').find('.loading-info').html('已上传：' + percent + '%');
		                }
		            })
			            .then(function(resp) {
			                $(file).prop('disabled', false);
			                videoSrc = 'http://koucaiceping-video.oss-cn-beijing.aliyuncs.com/' + resp.name;

			                var $videoDom = $('<video src="'+ videoSrc +'" webkit-playsinline playsinline controls="controls"></video>');
			                $video.empty().append($videoDom);
			                $('.page-single-btn').hide();
			                $('.page-group-btn-wrap').show();
			                if (currentExam == 6) {
								$('#J_next_btn_group').hide();
								$('#J_finished_btn_group').show();
			                }
			                else {
			                	$('#J_next_btn_group').show();
								$('#J_finished_btn_group').hide();
			                }
			                $('#J_exam_video').find('.content-video-loading').hide();
			                $('#J_exam_video').find('.content-video-wrap').show();
			                examQuery.answerContentUrl = videoSrc;
			            })
			            .catch(function(resp) {
			                throw new Error(resp);
			            });
			    }
			}

			// 录制视频
			$('#record_input').on('change', function() {
				loadFile(this);
			});

			// 重录视频
			$('#re_record_input').on('change', function() {
				currentExamTimes++;
				if (currentExamTimes >= 3) {
					Layer.msg('每题重录机会只有2次哦~');
					return;
				}
				loadFile(this);
			});
			// 点击重录视频暂停
			$('#re_record_input').on('click', function() {
				$('#J_answerDemoUrl').find('[data-video-elem="player"]')[0].pause();
				$('#J_questionExplainUrl').find('[data-video-elem="player"]')[0].pause();
			});

			// 下一题
			$('#J_next_btn').on('click', function() {
				api.setExamInfo(examQuery).then((resp) => {
					if (resp.ret == "0") {
						if (nextExamType == 1) {
							window.location.href = '/examAudio.html?examCode=' + examCode;
						}
						else if (nextExamType == 2) {
							window.location.href = '/examVideo.html?examCode=' + examCode;
						}
					}
				});
			});

			// 提交
			$('#J_finished_btn').on('click', function() {
				api.setExamInfo(examQuery).then((resp) => {
					if (resp.ret == "0") {
						Layer.msg('您的试卷已经成功提交</br>请耐心等待评审结果');
			            setTimeout(function(){
			                window.location.href = "indiviInfo.html";
			            },3000);
					}
				});
			});
		}
	}
})();

pageEntry.initCheck();
pageEntry.initExamInfo();
pageEntry.bindEvent();
